package com.itheima.daiotuwang.controller;



import com.itheima.daiotuwang.pojo.JwtUtil;
import com.itheima.daiotuwang.pojo.Result;
import com.itheima.daiotuwang.pojo.User;
import com.itheima.daiotuwang.service.UserService;
import com.itheima.daiotuwang.utils.Md5Util;
import jakarta.validation.constraints.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {


    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$")String password){
          //查询用户名是否存在
            User u = userService.findByUserName(username);
           if(u==null){
               //没有占用
               //注册
                userService.register(username,password);
                return  Result.success();
           }
           else {
               //占用
               return Result.error("用户名已被占用");
           }
          //注册
    }

    @PostMapping("login")
    public Result login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$")String password){
        //检查用户
        System.out.println(username);
        System.out.println(password);
        User u = userService.findByUserName(username);
        if(u==null){
            //没有占用
            //登录
            return  Result.error("用户名错误或者密码错误1");
        }
        //判断密码是否正确
        if(Md5Util.getMD5String(password).equals(u.getPassword())){
            //登录成功，但是这边注意一下需要有个叫做用户令牌的东西
            Map<String, Object> claims = new HashMap<>();
            claims.put("username",username);

            String token = JwtUtil.genToken(claims);

            return Result.success(token);
            }
        else {
           //登录失败
            return Result.error("用户名错误或者密码错误2");

        }

    }

}
